<template>
    <view class="footprint-page">
        <!-- 状态栏占位 -->
        <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

        <!-- 自定义导航栏 -->
        <view class="custom-nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
            <view class="nav-back" @click="goBack">
                <uni-icons type="left" size="20" color="#333333"></uni-icons>
            </view>
            <view class="nav-title">足迹</view>
        </view>

        <!-- 内容区域 -->
        <scroll-view class="content-scroll" scroll-y :scroll-top="scrollTop">
            <!-- 日历部分 -->
            <view class="calendar-controls">
                <view class="control-button" @click="prevMonth">
                    <uni-icons type="left" size="14" color="#333"></uni-icons>
                </view>
                <view class="month-year-display">
                    {{ currentYear }}年{{ currentMonth + 1 }}月
                </view>
                <view class="control-button" @click="nextMonth">
                    <uni-icons type="right" size="14" color="#333"></uni-icons>
                </view>
            </view>
            <view class="calendar-container">
                <view class="calendar-header">
                    <view v-for="(day, index) in weekDays" :key="index" class="day-header">{{ day }}</view>
                </view>
                <view class="calendar-body" :class="{ 'collapsed': isCollapsed }">
                    <view v-for="(day, index) in displayDays" :key="index" class="day-cell" :class="{
                        'current-month': day.isCurrentMonth
                    }" @click="handleDayClick(day)">
                        <view class="day-number" :class="{ 'today': day.isToday }">
                            {{ day.value }}
                        </view>
                    </view>
                </view>
                <view class="calendar-footer">
                    <view class="calendar-divider"></view>
                    <view class="collapse-btn" @click="toggleCollapse">
                        <image class="arrow-icon"
                            :src="isCollapsed ? (public_img + '/img/下箭头.png') : (public_img + '/img/上箭头.png')"
                            mode="aspectFit"></image>
                    </view>
                </view>
            </view>

            <!-- 足迹记录列表（按日期分组） -->
            <view class="records-container">
                <view v-for="(dateGroup, dateIndex) in groupedRecords" :key="dateIndex" class="date-group">
                    <view class="date-header">{{ formatChineseDate(dateGroup.date) }}</view>
                    <view class="record-list">
                        <view v-for="(record, recordIndex) in dateGroup.records" :key="recordIndex" class="record-item"
                            @click="goToProductDetail(record)">
                            <image class="record-image" :src="record.img || public_img + '/img/default_goods.png'"
                                mode="aspectFill"></image>
                            <view class="record-info">
                                <view class="record-title">{{ record.title || record.name }}</view>
                                <view class="record-bottom">
                                    <view class="record-desc">{{ record.synopsis || record.description || '' }}</view>
                                    <view class="record-price">¥{{ record.price || 0 }}</view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 空标签占位 -->
            <view style="height: 50rpx;"></view>
            <!-- 无数据提示 -->
            <view v-if="groupedRecords.length === 0 && !loading" class="no-records">
                <text>暂无浏览记录</text>
            </view>
        </scroll-view>
    </view>
</template>

<script>
import { userApi } from '@/api/indexAPI.js';
import { public_img } from '@/static/public.js';

export default {
    data() {
        return {
            public_img: public_img,
            statusBarHeight: 0,
            weekDays: ['日', '一', '二', '三', '四', '五', '六'],
            days: [],
            displayDays: [],
            currentYear: new Date().getFullYear(),
            currentMonth: new Date().getMonth(),
            selectedDate: null,
            allRecords: [],
            groupedRecords: [],
            loading: false,
            scrollTop: 0,
            isCollapsed: false,
            todayRowIndex: 0 // 当天所在的行索引
        };
    },
    computed: {
        // 根据收起状态决定显示的日期
        computedDisplayDays() {
            if (this.isCollapsed) {
                // 收起时只显示当天所在的那一行（7天）
                const startIndex = this.todayRowIndex * 7;
                return this.days.slice(startIndex, startIndex + 7);
            }
            return this.days;
        }
    },
    watch: {
        computedDisplayDays: {
            handler(newVal) {
                this.displayDays = newVal;
            },
            immediate: true
        },
        days: {
            handler() {
                this.updateDisplayDays();
            },
            immediate: true
        }
    },
    onLoad() {
        this.getStatusBarHeight();
        this.initCalendar();
        this.fetchRecords();
    },
    methods: {
        // 获取状态栏高度
        getStatusBarHeight() {
            try {
                const systemInfo = uni.getSystemInfoSync();
                this.statusBarHeight = systemInfo.statusBarHeight || 0;
            } catch (err) {
                console.error('获取状态栏高度失败', err);
                this.statusBarHeight = 20;
            }
        },
        // 返回
        goBack() {
            uni.navigateBack();
        },
        // 获取足迹数据
        async fetchRecords() {
            this.loading = true;
            try {
                const res = await userApi.getFootprint();
                console.log("获取足迹数据:", res);

                if (res.code === 1 && res.data) {
                    // 处理API返回的数据格式
                    this.allRecords = res.data.reduce((acc, dateItem) => {
                        if (dateItem.list && dateItem.list.length > 0) {
                            const dateRecords = dateItem.list.map(record => ({
                                date: this.formatDateFromAPI(dateItem.date),
                                title: record.title || record.name,
                                synopsis: record.synopsis || record.description,
                                price: record.price,
                                img: record.img && record.img.startsWith('http')
                                    ? record.img
                                    : (public_img + (record.img || '')),
                                id: record.id,
                                ct: record.ct
                            }));
                            return [...acc, ...dateRecords];
                        }
                        return acc;
                    }, []);

                    // 按日期分组
                    this.groupRecordsByDate();
                } else {
                    console.log("获取足迹数据失败:", res.msg || res.message);
                    this.allRecords = [];
                    this.groupRecordsByDate();
                }
            } catch (error) {
                console.error("获取足迹数据异常:", error);
                this.allRecords = [];
                this.groupRecordsByDate();
            } finally {
                this.loading = false;
            }
        },
        // 按日期分组记录
        groupRecordsByDate() {
            const grouped = {};
            this.allRecords.forEach(record => {
                if (!grouped[record.date]) {
                    grouped[record.date] = [];
                }
                grouped[record.date].push(record);
            });

            // 转换为数组并按日期倒序排列
            this.groupedRecords = Object.keys(grouped)
                .sort((a, b) => new Date(b) - new Date(a))
                .map(date => ({
                    date: date,
                    records: grouped[date]
                }));
        },
        // 格式化API返回的日期
        formatDateFromAPI(apiDate) {
            if (!apiDate) return '';
            const datePart = apiDate.split(' ')[0];
            return datePart.replace(/\//g, '-');
        },
        // 格式化日期为中文格式 (9月22日)
        formatChineseDate(dateStr) {
            if (!dateStr) return '';
            const date = new Date(dateStr);
            return `${date.getMonth() + 1}月${date.getDate()}日`;
        },
        // 比较两个日期是否是同一天
        isSameDay(dateStr1, dateStr2) {
            if (!dateStr1 || !dateStr2) return false;
            return dateStr1 === dateStr2;
        },
        // 格式化日期为YYYY-MM-DD
        formatDate(date) {
            if (!(date instanceof Date)) {
                date = new Date(date);
            }
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        // 处理日期点击
        handleDayClick(day) {
            if (!day.isCurrentMonth) return;
            this.selectedDate = day.date;
            // 如果收起状态，更新显示的行
            if (this.isCollapsed) {
                this.updateDisplayDays();
            }
            // 滚动到对应日期的记录
            this.scrollToDate(day.date);
        },
        // 滚动到指定日期
        scrollToDate(date) {
            // 这里可以实现滚动到对应日期记录的功能
            // 暂时只更新选中状态
        },
        // 初始化日历
        initCalendar() {
            const year = this.currentYear;
            const month = this.currentMonth;
            const today = new Date();
            const todayStr = this.formatDate(today);

            // 默认选中今天
            if (!this.selectedDate) {
                this.selectedDate = todayStr;
            }

            const firstDay = new Date(year, month, 1);
            const daysInMonth = new Date(year, month + 1, 0).getDate();
            const startDay = firstDay.getDay();

            const daysArray = [];

            // 上个月的日期
            const prevMonthDays = new Date(year, month, 0).getDate();
            for (let i = startDay - 1; i >= 0; i--) {
                const date = new Date(year, month - 1, prevMonthDays - i);
                const dateStr = this.formatDate(date);
                daysArray.push({
                    value: prevMonthDays - i,
                    isCurrentMonth: false,
                    isToday: dateStr === todayStr,
                    date: dateStr
                });
            }

            // 当前月的日期
            for (let i = 1; i <= daysInMonth; i++) {
                const date = new Date(year, month, i);
                const dateStr = this.formatDate(date);
                daysArray.push({
                    value: i,
                    isCurrentMonth: true,
                    isToday: dateStr === todayStr,
                    date: dateStr
                });
            }

            // 下个月的日期
            const totalCells = 42;
            const remainingCells = totalCells - daysArray.length;
            for (let i = 1; i <= remainingCells; i++) {
                const date = new Date(year, month + 1, i);
                const dateStr = this.formatDate(date);
                daysArray.push({
                    value: i,
                    isCurrentMonth: false,
                    isToday: dateStr === todayStr,
                    date: dateStr
                });
            }

            this.days = daysArray;
            // 计算当天所在的行索引
            this.calculateTodayRowIndex();
            this.updateDisplayDays();
        },
        // 计算当天所在的行索引
        calculateTodayRowIndex() {
            const today = new Date();
            const todayStr = this.formatDate(today);
            const todayIndex = this.days.findIndex(day => day.date === todayStr);
            if (todayIndex >= 0) {
                this.todayRowIndex = Math.floor(todayIndex / 7);
            } else {
                // 如果当前月份没有今天，则使用选中日期或第一行
                if (this.selectedDate) {
                    const selectedIndex = this.days.findIndex(day => day.date === this.selectedDate);
                    if (selectedIndex >= 0) {
                        this.todayRowIndex = Math.floor(selectedIndex / 7);
                    } else {
                        this.todayRowIndex = 0;
                    }
                } else {
                    this.todayRowIndex = 0;
                }
            }
        },
        // 更新显示的日期
        updateDisplayDays() {
            if (this.isCollapsed) {
                // 收起时，优先显示当天所在的行，如果没有当天则显示选中日期所在的行
                let rowIndex = this.todayRowIndex;
                if (this.selectedDate) {
                    const selectedIndex = this.days.findIndex(day => day.date === this.selectedDate);
                    if (selectedIndex >= 0) {
                        rowIndex = Math.floor(selectedIndex / 7);
                    }
                }
                const startIndex = rowIndex * 7;
                this.displayDays = this.days.slice(startIndex, startIndex + 7);
            } else {
                this.displayDays = this.days;
            }
        },
        // 切换收起/展开
        toggleCollapse() {
            this.isCollapsed = !this.isCollapsed;
            this.updateDisplayDays();
        },
        // 上个月
        prevMonth() {
            if (this.currentMonth === 0) {
                this.currentMonth = 11;
                this.currentYear--;
            } else {
                this.currentMonth--;
            }
            this.initCalendar();
        },
        // 下个月
        nextMonth() {
            if (this.currentMonth === 11) {
                this.currentMonth = 0;
                this.currentYear++;
            } else {
                this.currentMonth++;
            }
            this.initCalendar();
        },
        // 跳转到商品详情
        goToProductDetail(record) {
            if (record.id) {
                uni.navigateTo({
                    url: `/pages/product/index?id=${record.id}`
                });
            }
        }
    }
};
</script>

<style lang="scss" scoped>
.footprint-page {
    width: 100%;
    min-height: 100vh;
    background-color: #f5f5f5;
}

/* 状态栏占位 */
.status-bar {
    width: 100%;
    background-color: #ffffff;
}

/* 自定义导航栏 */
.custom-nav-bar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    background-color: #ffffff;
    border-bottom: 1px solid #f0f0f0;
}

.nav-back {
    position: absolute;
    left: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 44px;
    height: 44px;
    z-index: 1001;
}

.nav-title {
    font-size: 18px;
    font-weight: 700;
    color: #333333;
}

/* 内容区域 */
.content-scroll {
    margin-top: 44px;
}

/* 日历容器 */
.calendar-container {
    background: #ffffff;
    padding: 20rpx 0px;
}

.calendar-controls {
    display: flex;
    align-items: center;
    justify-content: center;
}

.control-button {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.month-year-display {
    font-size: 28rpx;
    font-weight: 500;
    color: #333;
}

.calendar-header {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    text-align: center;
    margin-bottom: 10rpx;
}

.day-header {
    font-size: 24rpx;
    color: #666;
    padding: 10rpx 0;
}

.calendar-body {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 8rpx;
}

.day-cell {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 3px;
}

.day-number {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 26rpx;
    color: #989898;
    width: 100%;
    height: 100%;
    min-height: 50rpx;
}

.day-cell:not(.current-month) .day-number {
    color: #ccc;
}

.day-number.today {
    background-color: #ff8d1a;
    color: #ffffff;
    font-weight: 500;
    border-radius: 50%;
    aspect-ratio: 1;
    width: 50rpx;
    height: 50rpx;
    min-width: 50rpx;
    min-height: 50rpx;
}

.calendar-body {
    padding-bottom: 10rpx;
}

.calendar-footer {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 10rpx;
    position: relative;
}

.calendar-divider {
    width: 100%;
    height: 1px;
    background-color: #f0f0f0;
    margin-bottom: 10rpx;
}

.collapse-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 60rpx;
    height: 60rpx;
    background-color: #f5f5f5;
    border-radius: 50%;
    transition: all 0.3s ease;
    position: absolute;
    top: -10px;
    right: 35px;
}

.collapse-btn:active {
    background-color: #e8e8e8;
}

.arrow-icon {
    width: 20px;
    height: 20px;
}

.date-header {
    font-size: 30rpx;
    font-weight: 500;
    color: #333;
    margin: 20rpx 0;
    padding-left: 10rpx;
}

.record-list {
    background: #ffffff;
    border-radius: 8px;
    overflow: hidden;
}

.record-item {
    display: flex;
    padding: 20rpx;
    border-bottom: 1px solid #f0f0f0;
}

.record-item:last-child {
    border-bottom: none;
}

.record-image {
    width: 120rpx;
    height: 120rpx;
    border-radius: 8rpx;
    margin-right: 20rpx;
    flex-shrink: 0;
}

.record-info {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.record-title {
    font-size: 28rpx;
    color: #505050;
    font-weight: 350;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.record-bottom {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}

.record-desc {
    font-size: 24rpx;
    color: #999;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    flex: 1;
    margin-right: 20rpx;
}

.record-price {
    font-size: 24rpx;
    color: #ff0000;
    flex-shrink: 0;
}

/* 无数据提示 */
.no-records {
    text-align: center;
    padding: 100rpx 0;
    color: #999;
    font-size: 28rpx;
}
</style>
